<?php

namespace App\Http\Controllers;

use App\Models\Device;
use App\Models\DeviceGroupAdd;
use App\Models\DeviceGroupSentence;
use App\Models\DeviceGroupTask;
use App\Models\Sentence;
use App\Models\Sns;
use App\Models\Qq;
use Carbon\Carbon;
use Validator;
use App\Tools\Instagraph;
use App\Models\DeviceGroup;
use Illuminate\Http\Request;

class DeviceGroupsController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    $query = DeviceGroup::with('devices', 'tasks', 'sentences', 'deviceGroupAdd')
      ->where('name', 'like', '%' . $request->name . '%')
      ->orderBy('name');
    if ($request->page) {
      $deviceGroups = $query->paginate(10)->toArray();
    } else {
      $deviceGroups = $query->get()->toArray();
    }
    return $this->success(0, '', $deviceGroups);
  }


    public function groupWechat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:device_groups,id',
            'group_wechat' => 'required|between:1,190',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        DeviceGroupAdd::where('device_group_id',$request->id)->update(['group_wechat'=>$request->group_wechat]);
        return $this->success(0, '成功');
    }
    public function getGroupWechat(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'imei' => 'required|exists:devices,imei'
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $device = Device::where('imei',$request->imei)->first();
        if($device->device_group_id){
            $group_wechat = DeviceGroupAdd::where('device_group_id',$device->device_group_id)->first();
            if($group_wechat) $group_wechat = $group_wechat->group_wechat;
            else return $this->failure(-1,'分组不存在');
            return $this->success(0, '成功',$group_wechat);
        }else return $this->failure(-1,'此imei无分组');
    }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validator = Validator::make($request->all(), [
        'name' => 'required|between:1,100',
        'desc' => 'required|between:1,190',
        'device_group_id' => 'sometimes|exists:device_groups,id',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $deviceGroup = new DeviceGroup();
    $deviceGroup->name = $request->name;
    $deviceGroup->desc = $request->desc;
    if($request->device_group_id){
        $deviceGroup->task_is_circle = DeviceGroup::where('id',$request->device_group_id)->first()->task_is_circle;
        $deviceGroup->save();
        $id = $deviceGroup->id;
        $tasks = DeviceGroupTask::where('device_group_id',$request->device_group_id)->get()->toArray();
        foreach ($tasks as $key => $val){
            $tasks[$key]['device_group_id']=$id;
            unset($tasks[$key]['id']);
        }
        DeviceGroupTask::insert($tasks);
    }
    $deviceGroup->save();
    $deviceGroupAdd = new DeviceGroupAdd();
    $deviceGroupAdd->device_group_id = $deviceGroup->id;
    $deviceGroupAdd->save();
    return $this->success(0, 'OK', $deviceGroup);
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request $request
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    $validator = Validator::make($request->all(), [
      'name' => 'sometimes|required|between:1,100',
      'desc' => 'sometimes|required|between:1,190',
      'task_is_circle' => 'sometimes|required|boolean',
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $deviceGroup = DeviceGroup::findOrFail($id);
    $request->name && $deviceGroup->name = $request->name;
    $request->desc && $deviceGroup->desc = $request->desc;
    isset($request->task_is_circle) && $deviceGroup->task_is_circle = $request->task_is_circle;
    if($request->device_group_id && $request->device_group_id != $id){
        $deviceGroup->task_is_circle = DeviceGroup::where('id',$request->device_group_id)->first()->task_is_circle;
        DeviceGroupTask::where('device_group_id',$id)->delete();
        $tasks = DeviceGroupTask::where('device_group_id',$request->device_group_id)->get()->toArray();
        foreach ($tasks as $key => $val){
            $tasks[$key]['device_group_id']=$id;
            unset($tasks[$key]['id']);
        }
        DeviceGroupTask::insert($tasks);
    }
    $deviceGroup->save();
    return $this->success(0, '', $deviceGroup);
  }

  public function show($id)
  {
    $deviceGroup = DeviceGroup::findOrFail($id);
    return $this->success(0, '', $deviceGroup);
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  int $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    $devices = DeviceGroup::find($id)->devices;
    $devices->each(function ($device) {
      $device->device_group_id = 0;
      $device->save();
    });
    DeviceGroupTask::where('device_group_id',$id)->delete();
    DeviceGroupSentence::where('device_group_id',$id)->delete();
    DeviceGroupAdd::where('device_group_id',$id)->delete();
    Qq::where('qq_group_id',$id)->delete();
//    DeviceGroup::find($id)->devices()->delete();
    DeviceGroup::destroy($id);
    return $this->success(0, '');
  }

  public function getSns(Request $request)
  {
    $validator = \Validator::make($request->all(), [
      'device_id' => 'required|exists:devices,id'
    ]);
    if ($validator->fails()) {
      return $this->failure(-1, $validator->errors()->first());
    }
    $device = Device::findOrFail($request->device_id);
    $deviceGroup = DeviceGroup::findOrFail($device->device_group_id);
    $faker = $faker = app(\Faker\Generator::class);
    $destinationPath = 'uploads/images/';
    $publicPath = public_path() . '/';
    $convertDir = $destinationPath . 'converts/';
    if (!\File::isDirectory($publicPath . $convertDir)) {
      \File::makeDirectory($publicPath . $convertDir, $mode = 0777, true, true);
    }
    $sns = $deviceGroup->sns()
        ->with(['snsPics', 'snsVideo'])
        ->where('publish_start_time', '<=', Carbon::now()->toDateTimeString())
        ->where('publish_end_time', '>=', Carbon::now()->toDateTimeString())
        ->get();
    $this->deviceDetailedList($type=1,$detail_type=1,$request->device_id);
    $filtered_collections = $sns->filter(function($item) use($device) {
      return !$item->hasPostedByDevice($device->id);
    });

    if ($deviceGroup) $deviceGroup = $deviceGroup->toArray();
    $deviceGroup['sns'] = $filtered_collections->values()->first() ? $filtered_collections->values()->first()->toArray() : null;
    $deviceGroup = array_filter_recursive($deviceGroup);
    $deviceGroup['has_sns_video'] = !empty($deviceGroup['sns']['sns_video']) ? 1 : 0;
    $deviceGroup['has_sns'] = !empty($deviceGroup['sns']) ? 1 : 0;
    $deviceGroup['has_sns_pics'] = !empty($deviceGroup['sns']['sns_pics']) ? 1 : 0;
    $newPics = [];
    if (isset($deviceGroup['sns']) && !empty($deviceGroup['sns']['sns_pics'])) {
      $positions = ['north', 'northeast', 'east', 'southeast', 'south', 'southwest', 'west', 'northwest'];
      foreach ($deviceGroup['sns']['sns_pics'] as $key => $item) {
        $path = $publicPath . $destinationPath . $item['name'];
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $newName = str_random(10) . '.' . $type;
        $instagraph = Instagraph::factory($path, $publicPath . $convertDir . $newName);
        $instagraph->_output = $publicPath . $convertDir . $newName;
        $position = $faker->randomElement($positions);
        $fontSize = 2;
        $font = $faker->uuid();
        $instagraph->withText($position, $fontSize, $font);
        $newPics[$key]['image_name'] = $newName;
        $newPics[$key]['img_url'] = stripslashes(asset($convertDir . $newName));
      }
      $deviceGroup['sns']['sns_pics'] = $newPics;
      $deviceGroup['sns']['pic_count'] = count($newPics);
    }
    return $this->success(0, '', $deviceGroup);
  }
}
